package com.suse.ecommerce.serviceImp;

import com.suse.ecommerce.dao.SeckillMapper;
import com.suse.ecommerce.dao.SeckillOrderMapper;
import com.suse.ecommerce.dao.SeckillTimeMapper;
import com.suse.ecommerce.pojo.Order;
import com.suse.ecommerce.pojo.Seckill;
import com.suse.ecommerce.pojo.SeckillOrder;
import com.suse.ecommerce.pojo.SeckillTime;
import com.suse.ecommerce.service.SeckillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private SeckillTimeMapper seckillTimeMapper;

    @Autowired
    private SeckillMapper secKillMapper;

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    @Override
    public List<Seckill> querySekillByTime(Integer timeId) {

       //根据时间取出对应的商品
        List<Seckill> seckills = secKillMapper.querySeckillByTime(timeId);
        return seckills;
    }

    @Override
    public Seckill querySeckillById(long seckillId) {

        return secKillMapper.querySeckillById(seckillId);
    }

    @Override
    @Transactional(rollbackFor={RuntimeException.class, Exception.class})
    public SeckillOrder seckillConfrim(long seckillId, Integer userId, long addressId) {
        //根据seckillId查询出对应的秒杀商品
        Seckill seckill = secKillMapper.querySeckillById(seckillId);
        if(seckill.getStockCount()<=0){
            throw new RuntimeException("商品库存已售完");
        }

        //以下要用事务控制
        SeckillOrder seckillOrder=new SeckillOrder(null,seckill.getProduct().getTitle(),seckill.getProduct().getId(),
                seckill.getSeckillPrice(),
                seckill.getProduct().getImage(),addressId,userId,seckill.getId());

        seckillOrderMapper.insert(seckillOrder);

        //减少库存
        int i = secKillMapper.updateStock(seckillId);
        if(i<=0){
           throw  new RuntimeException("商品已售完");
        }

        return seckillOrder;
    }

}
